package com.nine.controller;

import com.nine.entity.Menu;
import com.nine.entity.MyReturn;
import com.nine.entity.Userinfo;
import com.nine.service.MenuService;
import com.nine.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author ：fmc / ssx
 * @date ：Created in 2022/6/25 15:37
 * @description：登录控制器
 * @modified By：
 * @version: 1.0
 */
@Controller
@RequestMapping("userLogin")
public class UserLoginController extends ControllerFather {
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private MenuService menuService;

    MyReturn myReturn= new MyReturn();

    @RequestMapping("login.do")
    @ResponseBody
    public MyReturn login(@RequestBody Map<String,Object> map, HttpSession session){
        boolean checkUser = userinfoService.checkUser(map);

        if(checkUser){
            // 登录成功之前，增强处理，将登录名保存到session中
            Userinfo userinfo = userinfoService.findUserInfoByName(map.get("loginName").toString());
            // 清除密码和盐值
            userinfo.setPassword("");
            userinfo.setSalt("");
            session.setAttribute("userInfo",userinfo);
            // 根据当前登录用户的身份，动态获取左侧菜单，并上传到session域中
            Map<String, List<Menu>> menuMap = menuService.findAllMenuByUserName(map.get("loginName").toString());
            session.setAttribute("menuMap",menuMap);
            // 登录成功
            return  super.getSuccessResult(myReturn);
        }
        return  super.getFailResult(myReturn);
    }

    @RequestMapping("logout.do")
    public String logout( HttpSession session){
        //session失效
        session.invalidate();
        //跳转到登录页面
        return "loginUser";
    }
}
